package com.ruoyi.team.service.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.team.mapper.CustomerMapper;
import com.ruoyi.team.domain.Customer;
import com.ruoyi.team.service.ICustomerService;

/**
 * 客户信息Service业务层处理
 *
 * @author Judy
 * @date 2022-11-27
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {


    @Autowired
    private ISysUserService userService;
    /**
     * 查询客户信息列表
     *
     * @param customer 客户信息
     * @return 客户信息
     */
    @Override
    public List<Customer> selectCustomerList(Customer customer) {

        List<Customer> customers = getBaseMapper().selectCustomerList(customer);
        //遍历集合
        for (Customer cus : customers) {
            //通过录入人id找到当前用户
            SysUser sysUser = userService.selectUserById(cus.getInputUser());
            //设置录入人名称
            cus.setInputUserName(sysUser.getNickName());
        }
        return customers;
    }
    /**
     * 新增客户信息
     * @param entity
     * @return
     */
    @Override
    public boolean save(Customer entity) {
        List<Customer> list = super.list();
        for (Customer customer : list) {
            if (customer.getCustomerName().equals(entity.getCustomerName())){
                throw new ServiceException("企业名称不能重复");
            }
        }
        LoginUser user = SecurityUtils.getLoginUser();
        entity.setInputUser(user.getUserId());
        entity.setInputTime(new Date());
        return super.save(entity);
    }

    @Override
    public Customer getById(Serializable id) {
        Customer customer = getBaseMapper().selectById(id);
        SysUser sysUser = userService.selectUserById(customer.getInputUser());
        customer.setInputUserName(sysUser.getNickName());
        return  customer;
    }
}
